<?php

namespace app\admin\model;

use think\Model;
use think\model\concern\SoftDelete;

class Category extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    public static $is_all = 0;
    public static function list($page = 1, $pageSize = 10)
    {
        $allCategories = self::alias('a')
            ->leftJoin('category b', 'a.pid = b.id')
            ->field('a.*, b.cate_name as parent_name')
            ->order('sort desc')
            ->select()
            ->toArray();
        $sortedCategories = self::sortCategories($allCategories);

        $total = count($sortedCategories);

        // 分页处理
        if (self::$is_all == 0) {
            $start = ($page - 1) * $pageSize;
            $currentPageData = array_slice($sortedCategories, $start, $pageSize);
        } else {
            $currentPageData = $sortedCategories;
            $pageSize = $total; 
        }

        foreach ($currentPageData as &$category) {
            $prefix = str_repeat('|— ', $category['level']); 
            $category['cate_name'] = $prefix . $category['cate_name'];
        }

        return [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => self::$is_all == 0 ? ceil($total / $pageSize) : 1,
            'data' => $currentPageData
        ];
    }
    public static function sortCategories($categories, $pid = 0, $level = 0)
    {
        $result = [];
        foreach ($categories as $category) {
            if ($category['pid'] == $pid) {
                $category['level'] = $level; 
                $result[] = $category;
                // 递归查找子分类
                $children = self::sortCategories($categories, $category['id'], $level + 1);
                $result = array_merge($result, $children);
            }
        }
        return $result;
    }
}
